import {
  Body,
  Controller,
  FileTypeValidator,
  Get,
  MaxFileSizeValidator,
  Param,
  ParseFilePipe,
  Post,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileService } from './file.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { PageQuery } from '../../../util/entity/page.entity';
import { File } from './entities/file.entity';

@Controller()
export class FileController {
  constructor(private readonly fileService: FileService) {}

  @Post('list')
  findAll(@Body() pageQuery: PageQuery<File>) {
    return this.fileService.findAll(pageQuery);
  }

  /**
   * 文件上传
   * @param file
   * @param filePath
   */
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(
    @UploadedFile(
      new ParseFilePipe({
        validators: [
          // 如果验证器的数量大幅增加，或者它们的选项使文件杂乱无章，
          // 您可以在一个单独的文件中定义此数组，并将其作为像fileValidators一样的命名常量导入此处。
          new MaxFileSizeValidator({
            maxSize: 1024 * 1024 * 2,
            message: '文件最大为2M',
          }),
          new FileTypeValidator({ fileType: /^image\// }),
        ],
      }),
    )
    file: Express.Multer.File,
    @Body('filePath') filePath: string,
  ) {
    return await this.fileService.writeFileTo(file, filePath);
  }

  /**
   * 从数据库中查找,某个文件夹里的图片
   */
  @Get('view/:path')
  getViews(@Param('path') path: string) {
    return this.fileService.getViews(path);
  }

  /**
   * 获取所有的文件夹
   */
  @Get('folders')
  getFolders() {
    return this.fileService.getFolders();
  }
}
